<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
       <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon></el-alert>
       <!-- 表单 -->
       <el-form ref="form" label-width="120px">
         <el-form-item label="选择商品分类：">
           <!-- 多级选择器 -->
          <el-cascader v-model="selectKeys" clearable :options="sortList" :props="prop"
            @change="changeSelect">
          </el-cascader>
         </el-form-item>
       </el-form>
       <!-- tabs标签页 -->
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="动态参数" name="only">
            <el-button style="margin:20px 0" type="primary" 
            :disabled="selectKeys.length != 3" @click="addPara">添加参数</el-button>
            <!-- 展开项的表格 -->
            <el-table style="width: 100%" border :data="onlyTableList">
              <el-table-column type="expand"  width="width">
                <template v-slot="{row}">
                  <el-tag
                      v-for="(item,index) in row.attr_vals" style="margin:0 5px;" 
                      @close="handleClose(item,row)" :key="index" closable>
                      {{item}}
                  </el-tag>
                  <!-- 可添加tag按钮 -->
                  <el-input class="input-new-tag" v-if="row.flag" v-model="inputValue"
                    ref="saveTagInput" size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" align="center" label="#" width="width">
              </el-table-column>
              <el-table-column align="center" prop="attr_name" label="参数名称" width="width">
              </el-table-column>
              <el-table-column align="center" label="操作" width="width">
                <template v-slot="{row}">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="editOnlySort(row)">修改</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteManyOrOnly(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="静态参数" name="many">
            <el-button style="margin:20px 0" type="primary" 
             :disabled="selectKeys.length != 3" @click="addAttr">
              添加属性
            </el-button>
            <!-- 展开项的表格 -->
            <el-table style="width: 100%" border :data="manyTableList">
              <el-table-column type="expand"  width="width">
                <template v-slot="{row}">
                  <el-tag
                    v-for="(item,index) in row.attr_vals" style="margin:0 5px;" 
                    @close="handleClose(item,row)" :key="index" closable>
                    {{item}}
                  </el-tag>
                  <!-- 可添加tag按钮 -->
                  <el-input class="input-new-tag" v-if="row.flag" v-model="inputValue"
                    ref="saveTagInput" size="small"
                    @keyup.enter.native="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" align="center" label="#" width="width">
              </el-table-column>
              <el-table-column align="center" prop="attr_name" label="参数名称" width="width">
              </el-table-column>
              <el-table-column align="center" label="操作" width="width">
                <template v-slot="{row}">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="editManySort(row)">修改</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteManyOrOnly(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加按钮的对话框 :before-close="handleClose"-->
    <el-dialog :title="scene==0 ? '添加动态参数' : '添加静态属性'" :visible.sync="dialogVisible" width="40%">
      <el-form ref="form" label-width="100px">
        <el-form-item :label="scene==0 ? '添加动态参数:' : '添加静态属性:'">
          <el-input v-model="addOrEditInfo.attr_name" placeholder="请输入名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :disabled="!addOrEditInfo.attr_name" @click="addParaOraddAttrSave">保 存</el-button>
      </span>
    </el-dialog>
    <!-- 修改按钮的对话框 :before-close="handleClose"-->
    <el-dialog :title="scene==0 ? '修改动态参数' : '修改静态属性'" :visible.sync="editDialog" width="30%">
      <el-form ref="form" label-width="100px">
        <el-form-item :label="scene==0 ? '修改动态参数:' : '修改静态属性:'">
          <el-input v-model="addOrEditInfo.attr_name" placeholder="请输入名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="!addOrEditInfo.attr_name" @click="saveEditDialog">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'params',
    data(){
      return {
        // 商品分类数据列表
        sortList:[],
        // 收集多级选择器选中的value
        selectKeys:[],
        // 多级选择器的展示数据的配置
        prop:{ 
            expandTrigger: 'hover',
            value: 'cat_id',
            label:'cat_name', 
            children: 'children'
        },
        // tabs默认选择的那个
        activeName:'only',
        // 请求的参数
        sel:['only'],
        // 将selectKeys收集到这个属性、修改参数的id、添加id的、删除的id请求的id
        sort:'',
        // 储存动态参数数据
        onlyTableList:[],
        // 储存静态参数的数据
        manyTableList:[],
        // 添加动态和静态按钮的对话框
        dialogVisible:false,
        // 控制修改动态、静态的对话框
        editDialog: false,
        // 控制动态、静态对话框展示的不同内容。0是动态、1是静态
        scene:0,
        // 收集添加对话框的数据
        addOrEditInfo:{
          attr_name:'',
          attr_sel: ['only']
        },
        // 收集被修改、删除的id
        attrId:'',
        // tag input值
        inputValue: ''
      }
    },
    methods:{
      async getSortList(){
        let {data:result} = await this.$API.get('categories',{type:3})
        if(result.meta.status == 200){
          this.sortList = result.data
        }
      },
      // 选择器选中改变时的回调
      async changeSelect(value){
        // 如果选的是两级，则不发请求，将要展示的数据清空
        if(this.selectKeys.length != 3){
          this.onlyTableList = []
          this.manyTableList = []
          this.selectKeys = []
          return
        }
        this.selectKeys = value
        this.sort = this.selectKeys[2]
        this.getSortOrAttr()
      },
      // 获取表格的数据
      async getSortOrAttr(){
         // 否则就发起获取参数列表的请求
        let {data:result} = await this.$API.get(`categories/${this.sort}/attributes`,{params:{sel:this.sel}})
        result.data.forEach(item => {
          // 如果是新添加的参数，是没有属性。应该赋值为空数组。而不是都给空字符串
          item.attr_vals = item.attr_vals? item.attr_vals.split(' '): []
          //  给每条添加通过属性控制自己的inpu和tag的显影
          item.flag = false
        })
        if(this.sel[0]=='only'){
          this.onlyTableList = result.data
        }else{
          this.manyTableList = result.data
        }
        
      },
      // tabs切换的回调
      async handleClick(val){
        // 如果多级选择器没有值为空，则不请求数据
        if(this.selectKeys.length ==  0)return
        const {sel,sort} = this
        if(val.name == 'only'){
         sel.splice(0,1,'only')
        //  请求动态参数的数据
         let {data:result} = await this.$API.get(`categories/${sort}/attributes`,{params:{sel}})
         if(result.meta.status !== 200){
          return this.$message.error('请求动态数据失败')
         }
          result.data.forEach(item => {
          // 如果是新添加的参数，是没有属性。应该赋值为空数组。而不是都给空字符串
          item.attr_vals = item.attr_vals? item.attr_vals.split(' '): []
          //  给每条添加通过属性控制自己的inpu和tag的显影
          item.flag = false
        })
        //  储存数据
         this.onlyTableList = result.data
        }else{
          sel.splice(0,1,'many') 
          // 请求静态属性的数据
          let {data:result} = await this.$API.get(`categories/${sort}/attributes`,{params:{sel}})
           result.data.forEach(item => {
          // 如果是新添加的参数，是没有属性。应该赋值为空数组。而不是都给空字符串
          item.attr_vals = item.attr_vals? item.attr_vals.split(' '): []
          //  给每条添加通过属性控制自己的inpu和tag的显影
          item.flag = false
        })
          if(result.meta.status !== 200){
            return this.$message.error('请求动态数据失败')
          }
          //  储存数据
          this.manyTableList = result.data
        }
      },
      // 添加动态参数的函数
      addPara(){
        this.scene = 0
        // 清空name
        this.addOrEditInfo.attr_name = ''
        this.dialogVisible = true
      },
      // 添加静态属性的函数
      addAttr(){
        this.scene = 1
        // 清空name
        this.addOrEditInfo.attr_name = ''
        this.dialogVisible = true
      },
      // 添加动态参数、静态属性对话框的保存按钮
      async addParaOraddAttrSave(){
        this.dialogVisible = false
        // 动态参数的保存
        if(this.scene ==0){
          this.addOrEditInfo.attr_sel.splice(0,1,'only')
          let {data:result} = await this.$API.post(`categories/${this.sort}/attributes`,this.addOrEditInfo)
          if(result.meta.status !==201){
            return this.$message.error('添加动态参数失败')
          }
          this.$message.success('添加动态参数成功')
          // 更新数据
          this.getSortOrAttr()
        }
        // 动态参数的保存
        if(this.scene ==1){
          this.addOrEditInfo.attr_sel.splice(0,1,'many')
          let {data:result} = await this.$API.post(`categories/${this.sort}/attributes`,this.addOrEditInfo)
          if(result.meta.status !==201){
            return this.$message.error('添加静态属性失败')
          }
          this.$message.success('添加静态属性成功')
          // 更新数据
          this.getSortOrAttr()
        }
      },
      // 修改动态参数的按钮
      editOnlySort(row){
        this.scene = 0
        // 清空数据
        this.addOrEditInfo.attr_name = ''
        this.addOrEditInfo.attr_name = row.attr_name
        this.attrId = row.attr_id
        this.editDialog = true
      },
      // 修改静态属性的按钮
      editManySort(row){
        this.scene = 1
        // 清空数据
        this.addOrEditInfo.attr_name = ''
        this.addOrEditInfo.attr_name = row.attr_name
        this.attrId = row.attr_id
        this.editDialog = true
      },
      // 修改动态参数、静态属性的保存按钮
      async saveEditDialog(){
        this.editDialog = false
        // 修改动态参数
        if(this.scene == 0){
          const {sort,attrId} = this
          this.addOrEditInfo.attr_sel.splice(0,1,'only')
          let {data:result} = await this.$API.put(`categories/${sort}d/attributes/${attrId}`,
          this.addOrEditInfo
          )
          if(result.meta.status !==200){
            return this.$message.error('修改动态参数失败')
          }
          this.$message.success('修改动态参数成功')
          // 更新数据
          this.getSortOrAttr()
        }
        // 修改静态属性
        if(this.scene == 1){
          const {sort,attrId} = this
          this.addOrEditInfo.attr_sel.splice(0,1,'many')
          let {data:result} = await this.$API.put(`categories/${sort}/attributes/${attrId}`,
          this.addOrEditInfo
          )
          if(result.meta.status !==200){
            return this.$message.error('修改静态属性失败')
          }
          this.$message.success('修改静态属性成功')
          // 更新数据
          this.getSortOrAttr()
        }
      },
      // 删除按钮
      async deleteManyOrOnly(row){
        let {data:result} = await this.$API.delete(`categories/${this.sort}/attributes/${row.attr_id}`)
        if(result.meta.status !== 200){
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        // 更新数据
        this.getSortOrAttr()
      },
      // 点击+tag按钮，显示input框
      showInput(row) {
        row.flag = true
        // 等DOM更新完，再获取input焦点
        this.$nextTick( () => {
          this.$refs.saveTagInput.focus()
        })
      },
       // 点击tag删除
      handleClose(item,row) {
        row.attr_vals.splice(row.attr_vals.indexOf(item), 1)
        this.editOrDelete(row)
      },
      // 发起编辑和删除参数的请求
      async editOrDelete(row){
          if(row.attr_sel== 'only'){
            await this.$API.put(`categories/${this.sort}/attributes/${row.attr_id}`,
            {attr_name:row.attr_name,attr_sel:'only',attr_vals:row.attr_vals.join(' ')})
          }else{
             await this.$API.put(`categories/${this.sort}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel:'many',attr_vals:row.attr_vals.join(' ')})
          }
      },
      // 失去焦点
      handleInputConfirm(row) {
        // 输入的值不能为空
        if (this.inputValue.trim()=='') {
          return this.$message('不能空')
        }
         // 给当前tag的数组追加一个属性
        row.attr_vals.push(this.inputValue)
        // 发起编辑参数请求
        this.editOrDelete(row)
        // 隐藏input、清空数据
        row.flag = false
        this.inputValue = ''
      }
    },
    mounted(){
      this.getSortList()
    }
}
</script>

<style>
.el-card{
  margin: 20px 0;
}
.el-cascader-panel{
  height: 260px;
}
.el-form{
  margin: 20px 0;
}
</style>